<template>
  <el-dialog v-model="viewDialogVisible" :title="title" width="600px" append-to-body @close="handleClose">
    <div class="header">
      <el-row>
        <el-col :span="12">
          <h3>代码管理基本信息</h3>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <div v-if="!localIsEdit">
            <el-button @click="localIsEdit = true">编辑</el-button>
          </div>
          <div v-else>
            <el-button type="primary" @click="handleSave">保存</el-button>
            <el-button @click="localIsEdit = false">取消</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-form label-width="120px" label-position="top">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="代码id">
            <el-input v-model="form.codeId" :disabled="!localIsEdit" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="代码名称">
            <el-input v-model="form.codeName" :disabled="!localIsEdit" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="创建时间">
            <el-input v-model="form.createTime" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="代码描述">
        <el-input type="textarea" v-model="form.codeDesc" :disabled="!localIsEdit" />
      </el-form-item>
      <el-form-item label="代码文件">
        <el-upload disabled :file-list="form.attachments" action="#" list-type="text" />
      </el-form-item>

      <el-form-item label="代码关联情况">
        <el-table :data="form.relatedItems" disabled style="width: 100%">
          <el-table-column prop="reqId" label="需求id" />
          <el-table-column prop="reqName" label="需求名称" />
          <el-table-column prop="creator" label="创建人" />
          <el-table-column prop="updateTime" label="更新时间" />
        </el-table>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits } from 'vue';

const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  },
  title: String,
  isEdit: Boolean
});
const localIsEdit = ref(props.isEdit);

const viewDialogVisible = defineModel();

// 定义表单数据，将父组件传递的data映射到表单中
const form = ref({
  codeId: '',
  reqId: '',
  creator: '',
  codeName: '',
  createTime: '',
  codeDesc: '',
  attachments: [],
  relatedItems: []
});

watch(
  [() => props.isEdit, () => props.data],
  ([newIsEdit, newData]) => {
    localIsEdit.value = newIsEdit;
    form.value = { ...form.value, ...newData };
  },
  { immediate: true }
);
// 关闭对话框时触发事件，通知父组件
const emits = defineEmits(['close']);
const handleClose = () => {
  viewDialogVisible.value = false;
  emits('close');
};
</script>
